import matplotlib.pyplot as plt

# 读取数据
def read_data(filename):
    x, interpolated, actual = [], [], []
    with open(filename, 'r') as file:
        for line in file:
            parts = line.strip().split()
            x.append(float(parts[0]))
            interpolated.append(float(parts[1]))
            actual.append(float(parts[2]))
    return x, interpolated, actual

# 绘制函数
def plot_functions(x, interpolated, actual, output_file, legend_label):
    plt.plot(x, interpolated, label=legend_label, marker='o')

# 主程序
if __name__ == "__main__":
    n_values = [2, 4, 6, 8]
    x_values_all = []
    interpolated_values_all = []
    actual_values = []

    # 读取数据并存储在对应的列表中
    for n in n_values:
        filename = f"./data/dataB_n{n}.txt"
        x, interpolated, actual = read_data(filename)
        x_values_all.append(x)  # 存储每个n值的x值
        interpolated_values_all.append(interpolated)  # 存储每个n值的插值结果
        actual_values.append(actual)  # 存储所有实际值

    # 绘制所有插值曲线和真实曲线
    plt.figure(figsize=(10, 6))
    for i, n in enumerate(n_values):
        x_values, interpolated_values = x_values_all[i], interpolated_values_all[i]
        plt.plot(x_values, interpolated_values, label=f'Interpolated n={n}', linestyle='--')

    # 绘制真实曲线
    plt.plot(x_values_all[0], actual_values[0], label='Actual', linestyle='-', marker='o')  

    # 设置图表标题和标签
    plt.title('Newton Interpolation vs Actual Function')
    plt.xlabel('x')
    plt.ylabel('f(x)')
    plt.legend()
    plt.grid(True)

    # 保存图像
    plt.savefig("./picture/2B.png")
    plt.close()
    print("Plot saved to 2B.png")